<template>
  <div>
    <a-card style="margin-bottom:10px">          
      <a-form layout="inline">
        <a-row :gutter="16" type="flex" justify="start">
          <a-col :span="6">
            <a-form-item label="名称：">
              <a-input type="text" v-model="params.name"> </a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="类型：">
              <a-radio-group v-model="params.state">
                <a-radio-button value="0">启用</a-radio-button>
                <a-radio-button value="1">禁用</a-radio-button>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item>
              <a-button type="primary" @click="searchData"> <a-icon type="search"></a-icon>搜索 </a-button>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <a-card>
      <a-spin tip="加载中，请稍候..." :spinning="loading">
        <a-button-group>
          <a-button
            type="primary"
            :disabled="tableSelected.type === 'button'"
            @click="addMenuClick"
            v-perm:sys:menu:add
          >
            <a-icon type="plus" />新增
          </a-button>
          <a-button 
            type="primary" 
            @click="editMenuClick"
            v-perm:sys:menu:edit
          > 
            <a-icon type="edit" />修改 
          </a-button>
          <a-button 
            type="danger" 
            @click="deleteMenuClick"
            v-perm:sys:menu:delete
          >
            <a-icon type="delete" />删除
          </a-button>
        </a-button-group>
        <a-table
          style="margin-top:10px"
          :customRow="customRow"
          :columns="header"
          :dataSource="data"
          rowKey="id"
          :defaultExpandedRowKeys="expandedRowKeys"
          :rowSelection="rowSelection"
          :pagination="false"
        />
      </a-spin>
    </a-card>
    <a-modal v-model="showMenuModal" :title="modalTitle" @ok="handleOk">
      <add-menu v-bind="modalFormProps" ref="modalForm"></add-menu>
    </a-modal>
  </div>
</template>

<script>
  import AddMenu from './menu/AddMenu'
  export default {
    name: 'SysMenu',
    components: {
      AddMenu,
    },
    data() {
      var vm = this;
      return {
        params: {
          name: '',
          state: ''
        },
        loading: false,
        tableSelected: {},
        header: [
          {
            title: '名称',
            dataIndex: 'title',
            customRender: (text, record, index) => {
              return (
                <span>
                  {
                    record.icon ? (
                      <a-icon type={record.icon}></a-icon>
                    ) : ''
                  }
                  &nbsp;<span>{text}</span>
                </span>
              )
            }
          },
          {
            title: '访问路径',
            dataIndex: 'path'
          },
          {
            title: '类型',
            dataIndex: 'type',
            customRender: function(text){
              if(text === 'column'){
                return(
                  <a-tag color="blue">目录</a-tag>
                )
              }else if(text === 'menu'){
                return(
                  <a-tag color="green">菜单</a-tag>
                )
              }else if(text === 'button'){
                return(
                  <a-tag color="orange">按钮</a-tag>
                )
              }
            }
          },
          {
            title: '组件标识',
            dataIndex: 'label'
          },
          {
            title: '权限标识',
            dataIndex: 'permName'
          },
          {
            title: '状态',
            dataIndex: 'state',
            customRender: function(text){
              if(text === true){
                return(
                  <a-tag color="blue">显示</a-tag>
                )
              }else if(text === 'menu'){
                return(
                  <a-tag color="red">隐藏</a-tag>
                )
              }
            }
          },
          {
            title: "排序",
            dataIndex: "order"
          },
          {
            title: '操作',
            dataIndex: 'opts',
            customRender: (text, row, index) => {
              return (
                <a-button-group>
                  {
                    row.type != 'button' && this.$hasPerm('sys:menu:add') ? (
                      <a-tooltip title="新增">
                        <a-button
                          type="primary"
                          size="small"
                          icon="plus"
                          onClick={() => {
                            this.tableSelected = row
                            this.addMenuClick()
                          }}
                        />
                      </a-tooltip>
                    ) : ''
                  }
                  {
                    this.$hasPerm('sys:menu:edit') ? (
                      <a-tooltip title="修改">
                        <a-button
                          type="primary"
                          size="small"
                          icon="edit"
                          onClick={() => {
                            this.tableSelected = row
                            this.editMenuClick()
                          }}
                        />
                      </a-tooltip>
                    ) : ''
                  }
                  {
                    this.$hasPerm('sys:menu:delete') ? (
                      <a-tooltip title="删除">
                        <a-button
                          type="danger"
                          size="small"
                          icon="delete"
                          onClick={() => {
                            this.tableSelected = row
                            this.deleteMenuClick()
                          }}
                        />
                      </a-tooltip>
                    ) : ''
                  }
                </a-button-group>
              )
            }
          }
        ],
        data: [],
        expandedRowKeys: [],
        rowSelection: {
          type: 'radio',
          selectedRowKeys: [],
          onChange: (selectedRowKeys, selectedRows) => {
            vm.rowSelection.selectedRowKeys = selectedRowKeys
            vm.tableSelected = selectedRows[0]
          }
        },
        showMenuModal: false,
        modalTitle: '',
        modalTreeData: [],
        treeFilterFlag: false, // 菜单树是否已过滤
        parentTreeSelected: {},
      }
    },
    computed: {
      modalFormProps() {
        return {
          treeData: this.modalTreeData,
          expandedNodes: this.expandedRowKeys,
          menuType: '',
          openType: ''
        }
      }
    },
    watch: {
      showMenuModal (newVal) {
        if (newVal) {
          this.$nextTick(() => {
            let modalForm = this.$refs.modalForm;
            modalForm.form.setFieldsValue(this.modalFormParams)
          })
        }
      }
    },
    methods: {
      searchData(){
        this.$message.info('你点击了搜索按钮')
        // let params = {}
        this.getData();
      },
      getData() {
        this.loading = true;
        // 获取用户数据
        this.axios({
          url: '/system/menu/list',
          method: 'get'
        }).then(res => {
          this.data = res;
          this.loading = false
          this.expandedRowKeys.push(...this.data.map(item => item.id))

          this.modalTreeData = [{ id: '0', title: '主菜单' }]
          this.modalTreeData[0].children = JSON.parse(JSON.stringify(res))
          this.makeTreeData(this.modalTreeData)
        })
  
      },
      makeTreeData (data) {
        // 修改为antd控件需要的不同属性名
        for (let i = data.length - 1; i >= 0; i--) {
          var item = data[i]
          item.value = item.title
          item.key = item.id
          if (item.children) {
            this.makeTreeData(item.children)
          }
        }
      },
      customRow(record){
        return {
          on: {
            click: (event) => {
              this.rowSelection.selectedRowKeys = [record.id]
              this.tableSelected = record
            },
            dblclick: (event) => {},
            contextmenu: (event) => {},
            mouseenter: (event) => {},
            mouseleave: (event) => {}
          },
        };
      },
      initModalFormParams(){
        this.modalFormParams = {
          pid: '',
          pMenu: '',
          type: undefined,
          id: '',
          title: '',
          label: '',
          permName: '',
          icon: '',
          path: '',
          order: ''
        }
      },
      addMenuClick(){
        this.modalTitle = '新增'
        this.modalFormProps.openType = 'add'
        this.initModalFormParams()
        if(this.tableSelected.type === 'button'){
          this.$message.warn('按钮下不能创建子项')
          return
        }
        this.modalFormParams.pid = this.tableSelected.id ? this.tableSelected.id : '0'
        this.modalFormParams.title = this.tableSelected.title ? this.tableSelected.title : '主菜单'
        if(!this.tableSelected.type){
          this.modalFormParams.type = 'column'
          this.modalFormProps.menuType = 'column'
        }
        if(this.tableSelected.type === 'column'){
          this.modalFormParams.type = 'menu'
          this.modalFormProps.menuType = 'menu'
        }
        if(this.tableSelected.type === 'menu'){
          this.modalFormParams.type = 'button'
          this.modalFormProps.menuType = 'button'
        }
        this.showMenuModal = true
      },
      editMenuClick () {
        this.modalTitle = '编辑'
        this.modalFormProps.openType = 'edit'
        this.initModalFormParams()
        if (!this.tableSelected.id) {
          this.$message.warning('请选择要修改的菜单项')
          return
        }
        this.tableSelected = this.getMenuById(this.data, this.tableSelected.id)

        // 将选中的数据传递给addMenu弹窗备用
        for (const key in this.tableSelected) {
          if (this.modalFormParams.hasOwnProperty(key)) {
            this.modalFormParams[key] = this.tableSelected[key];
          }
        }
        var parentMenu = this.getMenuById(this.modalTreeData, this.modalFormParams.pid)
        this.modalFormParams.pMenu = parentMenu.title
        this.modalFormProps.menuType = this.modalFormParams.type
        this.showMenuModal = true
      },
      deleteMenuClick(){
        this.axios({
          url: '/system/menu/list/delete',
          method: 'post',
          data: this.tableSelected.id
        }).then(res => {
          this.$message.success(<span>删除 <b>{this.tableSelected.title}</b> 成功</span>)
        }).catch(err => {
          console.error(err)
        })
      },
      initModalFormData(){
        let modalForm = this.$refs.modalForm;
        modalForm.form.setFieldsValue(this.modalFormParams)
      },
      getMenuById (data, id) {
        if (id === null) return null
        for (var i = 0; i < data.length; i++) {
          if (data[i].id === id) {
            return data[i]
          }
          if (data[i].children) {
            var ret = null
            if ((ret = this.getMenuById(data[i].children, id))) {
              return ret
            }
          }
        }
      },
      handleOk(){
        const modalForm = this.$refs.modalForm;
        modalForm.handleSubmit().then(res => {
          if(res.code == 0){
            this.$message.success(res.msg)
          }
          this.showMenuModal = false
          modalForm.handleReset();
        }).catch(err => {
          console.error(err)
        });
      },
    },
    created () {
      this.getData();
    },
  }
</script>

<style lang="scss" scoped>

</style>